import hashlib
import time

from xunter_utils.xunter_requests import ChromeClient


class Kugou_Music(ChromeClient):
    def __init__(self):
        super().__init__()
        self.session.headers['referer'] = 'https://www.kugou.com/'

    def signatureParam(self,data_time,audio_id):
        s = [
                "NVPh5oo715z5DIWAeQlhMDsWXXQV4hwt",
                "appid=1014",
                f"clienttime={data_time}",
                "clientver=20000",
                "dfid=11RSEY2CgLti0sA1Z92b6r4m"
                f"encode_album_audio_id={audio_id}",
                "mid=e0210972f895f3892d9c59ccbd509bf2",
                "platid=4",
                "srcappid=2919",
                "token=7fbb03ae5cec5b48d2a8be0818cdc923a69fa4aaba15945634f230ad10444724"
                "userid=2159370610",
                "uuid=e0210972f895f3892d9c59ccbd509bf2"
                "NVPh5oo715z5DIWAeQlhMDsWXXQV4hwt",
]

        string = ''.join(s)
        h = hashlib.md5()  # 创建对象
        h.update(string.encode())  # 传入参数
        res = h.hexdigest()  # 编码
        # print(res, len(res))
        return res

    def get_video(self,data_time,audio_id):
        signature = self.signatureParam(data_time,audio_id)
        print(signature)
        res = self.send_request(
            url='https://wwwapi.kugou.com/play/songinfo',
            params={
                'srcappid': '2919',
                'clientver': '20000',
                'clienttime': data_time,
                'mid': 'e0210972f895f3892d9c59ccbd509bf2',
                'uuid': 'e0210972f895f3892d9c59ccbd509bf2',
                'dfid': '11RSEY2CgLti0sA1Z92b6r4m',
                'appid': '1014',
                'platid': '4',
                'encode_album_audio_id': audio_id,
                'token': '7fbb03ae5cec5b48d2a8be0818cdc923a69fa4aaba15945634f230ad10444724',
                'userid': '2159370610',
                'signature': signature,
            }
        )
        print(res.text)
        res_url = res.json()['data']['play_url']
        author_name = res.json()['data']['authors'][0]['author_name']
        audio_name = res.json()['data']['audio_name']
        print(res_url)
        video_res = self.send_request(res_url)
        with open(f'{audio_name}_{author_name}.mp3','wb+') as f:
            f.write(video_res.content)
        print(f'{audio_name} 下载完毕')


# if __name__ == '__main__':
#     client = Kugou_Music()
#     data_time = int(time.time()*1000)
#     client.get_video(data_time,'bqm1njb6')

